package edu.ahpu.propertymanage.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.ahpu.propertymanage.dataclass.*;
import edu.ahpu.propertymanage.pojo.*;
import edu.ahpu.propertymanage.service.*;
import edu.ahpu.propertymanage.util.GetID;
import edu.ahpu.propertymanage.util.WorkerStarUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.transaction.Transaction;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/project")
public class ProjectController {

    @Autowired
    GetID getID;

    @Autowired
    ProjectService projectService;

    @Autowired
    OwnerService ownerService;

    @Autowired
    WorkerService workerService;

    @Autowired
    DispatchService dispatchService;

    @Autowired
    SecurityService securityService;

    @Autowired
    RepairService repairService;

    @Autowired
    WorkerStarUtil workerStarUtil;

    @PostMapping("getrepairproject")
    public Project getRepairProject(String ownerId) {
        Owner owner = ownerService.getById(ownerId);
        String str = null;
        if (!("".equals(owner.getOwnerArea()) || owner.getOwnerArea() == null))
            str = owner.getOwnerArea() + "区" + owner.getOwnerDong() + "栋" + owner.getOwnerUnit() + "单元" + owner.getOwnerRoom() + "室";
        else
            str = owner.getOwnerDong() + "栋" + owner.getOwnerUnit() + "单元" + owner.getOwnerRoom() + "室";
        Project project = new Project();
        project.setProjectId(getID.getProjectId());
        project.setProjectDate(new Date());
        project.setProjectType("维修");
        project.setProjectPlace(str);
        return project;
    }

    @PostMapping("setrepairpoject")
    public String setRepairProject(@RequestBody Project project, String ownerId) {

        boolean bool = projectService.save(project);
        Repair repair = new Repair();
        String str = project.getProjectId();
        repair.setRepairId(str.substring(0, 5) + "R" + str.substring(6));
        repair.setOwnerId(ownerId);
        repair.setProjectId(project.getProjectId());

        boolean bool1 = repairService.save(repair);


        if (bool && bool1)
            return "success";
        else
            return "error";
    }


    //工人选择
    @GetMapping("getworkername")
    public List<WorkerNameOption> getWorkerName() {
        QueryWrapper<Worker> wrapper = new QueryWrapper<>();
        wrapper.select("worker_name");
        List<Worker> list = workerService.list(wrapper);
        List<WorkerNameOption> workerNameOptions = new ArrayList<>();
        for (Worker worker : list) {
            WorkerNameOption workerNameOption = new WorkerNameOption();
            workerNameOption.setValue(worker.getWorkerName());
            workerNameOption.setLabel(worker.getWorkerName());
            workerNameOptions.add(workerNameOption);
        }
        return workerNameOptions;
    }

    //获取表单
    @PostMapping("getprojectpro")
    public ProjectPro getDisProject(String tage) {
        ProjectPro projectPro = new ProjectPro();
        Project project = new Project();

        project.setProjectDate(new Date());
        project.setProjectId(getID.getProjectId());


        if ("D".equals(tage)) {
            projectPro.setWorkingId(getID.getDispatchId());
            project.setProjectType("派工");
        } else if ("S".equals(tage)) {
            projectPro.setWorkingId(getID.getSecurityId());
            project.setProjectType("安全检查");
        }
        projectPro.setProject(project);
        return projectPro;
    }

    //提交表单
    @PostMapping("setprojectpro")
    public String setDisProject(@RequestBody ProjectPro projectPro) {
        boolean probool = projectService.saveOrUpdate(projectPro.getProject());

        QueryWrapper<Worker> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Worker::getWorkerName, projectPro.getWorkerName());
        Worker worker = workerService.getOne(wrapper);
        boolean bool = false;
        if ("派工".equals(projectPro.getProject().getProjectType())) {
            Dispatch dispatch = new Dispatch();
            dispatch.setProjectId(projectPro.getProject().getProjectId());
            dispatch.setDispatchId(projectPro.getWorkingId());
            dispatch.setWorkerId(worker.getWorkerId());
            bool = dispatchService.saveOrUpdate(dispatch);
        } else if ("安全检查".equals(projectPro.getProject().getProjectType())) {
            Security security = new Security();
            security.setProjectId(projectPro.getProject().getProjectId());
            security.setSecurityId(projectPro.getWorkingId());
            security.setWorkerId(worker.getWorkerId());
            bool = securityService.saveOrUpdate(security);
        }
        if (probool && bool)
            return "success";
        else
            return "error";
    }


    //获取派工列表
    @PostMapping("showdispatch")
    public ShowProject showDispatch(@RequestBody PageSet pageSet) {
        ShowProject showProject = new ShowProject();
        List<ProjectPlus> list = new ArrayList<>();

        //获取派工的项目
        IPage<Project> projectIPage = new Page<>(pageSet.getCurrent(), pageSet.getSize());
        QueryWrapper<Project> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Project::getProjectType, "派工");
        projectIPage = projectService.page(projectIPage, wrapper);

        //获取派工表
        IPage<Dispatch> dispatchIPage = new Page<>(pageSet.getCurrent(), pageSet.getSize());
        dispatchIPage = dispatchService.page(dispatchIPage);

        for (int i = 0; i < projectIPage.getRecords().size(); i++) {
            //获取project
            ProjectPlus projectPlus = new ProjectPlus();
            projectPlus.setProject(projectIPage.getRecords().get(i));
            //获取dispatch
            projectPlus.setObject(dispatchIPage.getRecords().get(i));
            //获取workerName
            QueryWrapper<Worker> workerQueryWrapper = new QueryWrapper<>();
            workerQueryWrapper.lambda().eq(Worker::getWorkerId, dispatchIPage.getRecords().get(i).getWorkerId());
            Worker worker = workerService.getOne(workerQueryWrapper);
            projectPlus.setWorkerName(worker.getWorkerName());
            projectPlus.setWorkerStar(worker.getWorkerStar());

            //判断是否打分
            if (dispatchIPage.getRecords().get(i).getDispatchSatLevel() == null || "".equals(dispatchIPage.getRecords().get(i).getDispatchSatLevel()) || 0 == dispatchIPage.getRecords().get(i).getDispatchSatLevel()) {
                //获取是否工人回复
                if ("".equals(dispatchIPage.getRecords().get(i).getDispatchMsg()) || dispatchIPage.getRecords().get(i).getDispatchMsg() == null)
                    projectPlus.setIscallback(false);
                else {
                    projectPlus.setIscallback(true);
                }
            } else {
                projectPlus.setIssubmit(true);
                projectPlus.setIscallback(true);
            }

            list.add(projectPlus);
        }
        pageSet.setTotal(dispatchIPage.getTotal());
        showProject.setPageSet(pageSet);
        showProject.setProjectPlusList(list);
        return showProject;
    }

    //获取安全检查列表
    @PostMapping("showsecurity")
    public ShowProject showSecurity(@RequestBody PageSet pageSet) {
        //一个pageSet，一个List<Object>
        ShowProject showProject = new ShowProject();
        List<ProjectPlus> list = new ArrayList<>();

        //获取安全检查的项目
        IPage<Project> projectIPage = new Page<>(pageSet.getCurrent(), pageSet.getSize());
        QueryWrapper<Project> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Project::getProjectType, "安全检查");
        projectIPage = projectService.page(projectIPage, wrapper);

        //获取安全表
        IPage<Security> securityIPage = new Page<>(pageSet.getCurrent(), pageSet.getSize());
        securityIPage = securityService.page(securityIPage);

        for (int i = 0; i < projectIPage.getRecords().size(); i++) {
            //获取project
            ProjectPlus projectPlus = new ProjectPlus();
            projectPlus.setProject(projectIPage.getRecords().get(i));
            //获取dispatch
            projectPlus.setObject(securityIPage.getRecords().get(i));
            //获取workerName
            QueryWrapper<Worker> workerQueryWrapper = new QueryWrapper<>();
            workerQueryWrapper.lambda().eq(Worker::getWorkerId, securityIPage.getRecords().get(i).getWorkerId());
            Worker worker = workerService.getOne(workerQueryWrapper);
            projectPlus.setWorkerName(worker.getWorkerName());
            projectPlus.setWorkerStar(worker.getWorkerStar());


            //判断是否打分
            if (securityIPage.getRecords().get(i).getSecuritySatLevel() == null || "".equals(securityIPage.getRecords().get(i).getSecuritySatLevel()) || 0 == securityIPage.getRecords().get(i).getSecuritySatLevel()) {
                //获取是否工人回复
                if ("".equals(securityIPage.getRecords().get(i).getSecurityMsg()) || securityIPage.getRecords().get(i).getSecurityMsg() == null)
                    projectPlus.setIscallback(false);
                else {
                    projectPlus.setIscallback(true);
                }
            } else {
                projectPlus.setIssubmit(true);
                projectPlus.setIscallback(true);
            }

            list.add(projectPlus);
        }
        pageSet.setTotal(securityIPage.getTotal());
        showProject.setPageSet(pageSet);
        showProject.setProjectPlusList(list);
        return showProject;
    }

    //获取维修列表
    @PostMapping("showrepair")
    public ShowProject showRepair(@RequestBody PageSet pageSet) {
        //一个pageSet，一个List<Object>
        ShowProject showProject = new ShowProject();
        List<ProjectPlus> list = new ArrayList<>();

        //获取报修的项目
        IPage<Project> projectIPage = new Page<>(pageSet.getCurrent(), pageSet.getSize());
        QueryWrapper<Project> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Project::getProjectType, "维修");
        projectIPage = projectService.page(projectIPage, wrapper);

        //获取维修表
        List<Repair> repairs = repairService.list();
        IPage<Repair> repairIPage = new Page<>(pageSet.getCurrent(), pageSet.getSize());
        repairIPage = repairService.page(repairIPage);

        for (int i = 0; i < projectIPage.getRecords().size(); i++) {
            //获取project
            ProjectPlus projectPlus = new ProjectPlus();
            projectPlus.setProject(projectIPage.getRecords().get(i));
            //获取repair
            projectPlus.setObject(repairIPage.getRecords().get(i));
            //获取workerName
            QueryWrapper<Worker> workerQueryWrapper = new QueryWrapper<>();
            workerQueryWrapper.lambda().eq(Worker::getWorkerId, repairIPage.getRecords().get(i).getWorkerId());
            Worker worker = workerService.getOne(workerQueryWrapper);
            //判断是否有工人（管理员是否安排此次维修）
            if (worker != null) {
                projectPlus.setWorkerName(worker.getWorkerName());
                projectPlus.setWorkerStar(worker.getWorkerStar());
                projectPlus.setIshaveworker(true);
//                projectPlus.setIscallback(true);
                //判断是否打分
                if (repairIPage.getRecords().get(i).getRepairSatLevel() == null || "".equals(repairIPage.getRecords().get(i).getRepairSatLevel()) || 0 == repairIPage.getRecords().get(i).getRepairSatLevel()) {
                    //获取是否工人回复
                    if ("".equals(repairIPage.getRecords().get(i).getRepairMsg()) || repairIPage.getRecords().get(i).getRepairMsg() == null) {
                        projectPlus.setIssubmit(false);
                        projectPlus.setIscallback(false);
                    } else {
                        projectPlus.setIscallback(false);
                        projectPlus.setIssubmit(true);
                    }
                } else {//打分并回复
                    projectPlus.setIssubmit(true);
                    projectPlus.setIscallback(true);
                }
            } else {
                projectPlus.setIshaveworker(false);
                projectPlus.setIssubmit(false);
                projectPlus.setIscallback(false);
            }
            list.add(projectPlus);
        }

        pageSet.setTotal(repairIPage.getTotal());
        showProject.setPageSet(pageSet);
        showProject.setProjectPlusList(list);
        return showProject;
    }


    @PostMapping("updateprojectplus")
    public String updateProjectPlus(@RequestBody ProjectPlus projectPlus) {

        String string = JSONObject.toJSONString(projectPlus.getObject());
        Dispatch dispatch = JSON.parseObject(string, Dispatch.class);
        Security security = JSON.parseObject(string, Security.class);
        Repair repair = JSON.parseObject(string, Repair.class);

        boolean bool_s = securityService.updateById(security);
        boolean bool_d = dispatchService.updateById(dispatch);
        boolean bool_r = false;

        if (bool_s) {
            Worker worker = workerService.getById(security.getWorkerId());
            worker.setWorkerStar( workerStarUtil.workerStar(security.getWorkerId()));
            workerService.saveOrUpdate(worker);
        }
        if (bool_d) {
            Worker worker = workerService.getById(dispatch.getWorkerId());
            worker.setWorkerStar(workerStarUtil.workerStar(dispatch.getWorkerId()));
            workerService.saveOrUpdate(worker);
        }

        if (bool_s || bool_d)
            return "success";
        else {
            QueryWrapper<Worker> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(Worker::getWorkerName, projectPlus.getWorkerName());
            Worker worker = workerService.getOne(wrapper);
            repair.setWorkerId(worker.getWorkerId());
            bool_r = repairService.updateById(repair);
            worker.setWorkerStar(workerStarUtil.workerStar(repair.getWorkerId()));
            workerService.saveOrUpdate(worker);
            if (bool_r)
                return "success";
            else
                return "error";
        }
    }

    @PostMapping("deleteprojectplus")
    public String deleteProjectPlus(@RequestBody ProjectPlus projectPlus) {

        boolean bool = projectService.removeById(projectPlus.getProject().getProjectId());

        if (bool) {
            return "success";
        } else {
            return "error";
        }
    }

}
